import os.path

import xmindparser
from PyQt5.QtMultimedia import QSound
from openpyxl import Workbook
from PyQt5 import QtWidgets, uic
from PyQt5.QtWidgets import QMainWindow, QFileDialog, QHBoxLayout, QMessageBox


class ToolUi(QMainWindow):

    def __init__(self):
        super().__init__()
        self.ui = uic.loadUi("view/tool.ui")

        # 按钮绑定点击事件
        self.ui.btn_select_file.clicked.connect(self.select_file)
        self.ui.btn_process_file.clicked.connect(self.process_file)
        self.ui.select_from.clicked.connect(self.show_checkbox_dialog)
        self.ui.pushButton.clicked.connect(self.export_files)

        # 被选中的测试用例表头
        self.selected_items = []
        # 存储处理后的文件数据
        self.processed_files = []


        # 初始化变量
        self.selected_file_path = ""

    def select_file(self):
        """打开文件选择对话框"""
        file_path, _ = QFileDialog.getOpenFileName(
            self,
            "选择 XMind 文件",
            "",
            "XMind 文件 (*.xmind);;所有文件 (*)"
        )

        if file_path:
            self.selected_file_path = file_path
            self.ui.file_new.setText(f"已选择: {file_path}")
            self.ui.file_path.setText(file_path)
            self.ui.btn_process_file.setEnabled(True)

        else:
            self.ui.file_new.setText("未选择文件")
            self.ui.btn_process_file.setEnabled(False)

    def export_files(self):
        """导出处理后的Excel文件"""
        if not self.processed_file:
            QMessageBox.warning(self, "无文件可导出", "请先处理文件后再导出")
            return

        # 选择保存目录
        save_dir = QFileDialog.getExistingDirectory(
            self,
            "选择Excel保存目录",
            "",
            QFileDialog.ShowDirsOnly
        )

        if not save_dir:
            return

        # 导出所有处理过的文件
        exported_count = 0
        for file_data in self.processed_files:
            try:
                file_name = file_data['file_name']
                wb = file_data['workbook']

                # 构建保存路径
                save_path = os.path.join(save_dir, f"{file_name}.xlsx")

                # 保存Excel文件
                wb.save(save_path)
                exported_count += 1
                self.ui.log_area.append(f"已导出：{save_path}")

            except Exception as e:
                self.ui.log_area.append(f"导出失败：{file_data['file_name']} - {str(e)}")

        # 显示导出结果
        if exported_count > 0:
            QMessageBox.information(self, "导出成功", f"已成功导出 {exported_count} 个Excel文件到：\n{save_dir}")
        else:
            QMessageBox.warning(self, "导出失败", "所有文件导出失败，请查看日志")


    def process_file(self):
        """处理选中的文件（后续将添加解析功能）"""
        if not self.selected_file_path:
            return

        try:
            # 解析 XMind 文件
            content = xmindparser.xmind_to_dict(self.selected_file_path)

            # 创建 Excel 工作簿
            wb = Workbook()
            ws = wb.active
            ws.title = "XMind 内容"

            # 添加表头
            ws.append(self.selected_items)

            # 递归遍历所有主题
            def parse_topic(topic, level=1):
                title = topic.get('title', '')
                notes = topic.get('note', '')
                link = topic.get('link', '')
                ws.append([title, level, notes, link])

                # 处理子主题
                for subtopic in topic.get('topic', []):
                    parse_topic(subtopic, level + 1)

            # 从根主题开始解析
            for sheet in content:
                for topic in sheet['topic']['topics']:
                    parse_topic(topic)

            # 保存
            file_name = self.selected_file_path.split("/")[-1].split(".")[0]
            save_path = f"{file_name}.xlsx"
            wb.save(save_path)

            self.ui.file_new.setText(f"导出成功：{save_path}")

        except Exception as e:
            self.ui.file_new.setText(f"处理错误：{str(e)}")

    def show_checkbox_dialog(self):
        # 创建对话框
        dialog = QtWidgets.QDialog(self)
        dialog.setWindowTitle("选择测试用例表头")
        dialog.setFixedSize(400, 300)

        # 主垂直布局
        main_layout = QtWidgets.QVBoxLayout(dialog)

        # 创建网格布局用于放置复选框
        center_layout = QHBoxLayout()
        grid_layout = QtWidgets.QGridLayout()
        grid_layout.setHorizontalSpacing(80)  # 设置水平间隔

        # 定义复选框内容
        options = ["主模块", "子模块", "用例编号", "用例标题", "优先级", "前置条件", "操作步骤", "预期结果", "实际结果",
                   "等级", "备注", "状态", "测试执行人", "执行时间"]
        checkbox_list = []  # 保存复选框控件

        # 动态创建复选框
        for i, text in enumerate(options):
            row = i // 2
            col = i % 2
            cb = QtWidgets.QCheckBox(text)
            checkbox_list.append(cb)
            grid_layout.addWidget(cb, row, col)

        # 把 grid_layout 放入 center_layout 实现水平居中
        center_layout.addStretch()
        center_layout.addLayout(grid_layout)
        center_layout.addStretch()

        # 加入主布局
        main_layout.addLayout(center_layout)

        # “确定”按钮
        button_layout = QtWidgets.QHBoxLayout()
        button_layout.addStretch()
        confirm_btn = QtWidgets.QPushButton("确定")
        button_layout.addWidget(confirm_btn)
        button_layout.addStretch()
        main_layout.addLayout(button_layout)
        # confirm_btn = QtWidgets.QPushButton("确定", dialog)
        # confirm_btn.move(150, 450)

        # 点击确定按钮时收集勾选内容
        def handle_confirm():
            self.selected_items.clear()
            for cb in checkbox_list:
                if cb.isChecked():
                    self.selected_items.append(cb.text())

            # 显示结果
            if self.selected_items:
                QtWidgets.QMessageBox.information(self, "勾选结果", "你选择了: " + "、".join(self.selected_items))
                print(self.selected_items)
            else:
                QtWidgets.QMessageBox.information(self, "勾选结果", "你没有勾选任何选项")
            dialog.accept()

        confirm_btn.clicked.connect(handle_confirm)
        dialog.exec_()
